import type { TeacherDispatchType } from '../interface'
import { useLocalObservable, useObserver } from 'mobx-react'
import { history } from 'umi'
import { cancelDispatch, fetchTeacherDispatchDetail } from '../api'
import { useEffect } from 'react'
import { Dialog, Toast } from 'antd-mobile'
import { rpxToPx } from '@/utils/share'
import classNames from 'classnames'
import Btn from '@/components/Global/Btn'
import styles from './index.module.less'
import NavBar from '@/components/Global/NavBar'

/** 师资派遣详情 */
const TeacherDispatch = () => {
    const queryParams = history.location.query as { id: string }
    const store = useLocalObservable(() => ({
        /** 培训计划详细信息 */
        detail: {} as Partial<TeacherDispatchType.Detail>,

        async fetchTrainPlanDetailToStore() {
            const data = await fetchTeacherDispatchDetail(Number(queryParams.id))
            if (!data) return

            store.detail = data
        },
    }))

    useEffect(() => {
        const fetch = async () => {
            const tostShow = Toast.show({
                content: '加载中...',
                duration: 0,
            })
            await store.fetchTrainPlanDetailToStore()
            tostShow.close()
        }

        fetch()
    }, [store])

    /** 教师卡片 */
    const TeacherCard = (params: {
        dispatch?: TeacherDispatchType.DispatchState
        item?: TeacherDispatchType.TeacherDispatch
        header: React.ReactNode
        /** 点击派遣 */
        onCancelDispatch?: (id: number) => Promise<any>
        /** 点击取消派遣 */
        onDispatch?: () => void
    }) => {
        const { item, onCancelDispatch, header, onDispatch, dispatch } = params

        return (
            <div
                className={styles.teacherCard}
                onClick={() => item?.teacher_user_id || onDispatch?.()}
            >
                <div className={styles.teacherCard_header}>{header}</div>
                {item?.teacher_user_id ? (
                    <>
                        <div className={styles.teacherCard_item}>
                            <label>{item.realname || '-'}</label>
                            <span>{item.region || '-'}</span>
                            <div>{item.phone || '-'}</div>

                            {[0, 1, 2].includes(dispatch ?? -1) && (
                                <Btn
                                    style={{ marginTop: rpxToPx(24) }}
                                    size="small"
                                    fill="outline"
                                    shape="rounded"
                                    color="primary"
                                    task={async e => {
                                        e[0].stopPropagation()
                                        onCancelDispatch?.(Number(item.teacher_user_id))
                                    }}
                                >
                                    取消派遣
                                </Btn>
                            )}
                        </div>
                    </>
                ) : (
                    <div className={styles.teacherCard_dispatch}>待派遣</div>
                )}
            </div>
        )
    }

    /**
     * 派遣
     * @param code 培训师编码
     * @param teacher_id 培训师user_id
     */
    const onDispatch = async (code: number) => {
        history.push({
            pathname: '/teacherDispatch/dispatch',
            query: { id: queryParams.id, code: String(code) },
        })
    }

    /** 取消派遣 */
    const onCancelDispatch = async (id: number) => {
        await Dialog.confirm({
            closeOnMaskClick: true,
            title: '取消派遣',
            content: '是否需要取消派遣',
            cancelText: '取消',
            confirmText: '确认',
            onConfirm: async () => {
                try {
                    await cancelDispatch(Number(queryParams.id), {
                        gid: Number(queryParams.id),
                        teachers: [id],
                    })

                    /** 为什么要加这个定时器。因为【取消派遣后】重新请求到的数据，还是老的数据。可能是后端缓存原因。 */
                    await new Promise(r => setTimeout(r, 1000))

                    await store.fetchTrainPlanDetailToStore()

                    Toast.show({ icon: 'success', content: '操作成功' })
                } catch (error) {}
            },
        })
    }

    return useObserver(() => {
        return (
            <>
                <NavBar title="师资派遣详情" />

                <div className={styles.page}>
                    <div className={styles.plate}>
                        <div className={styles.plate_header}>{store.detail.name}</div>

                        <div className={styles.plate_content}>
                            <div className={styles.plate_content_field}>
                                <label>编码</label> <span>{store.detail.code}</span>
                            </div>
                            <div className={styles.plate_content_field}>
                                <label>地区</label> <span>{store.detail.region}</span>
                            </div>
                            <div className={styles.plate_content_field}>
                                <label>时间</label>
                                <span>
                                    {store.detail.begin_date} 至 {store.detail.end_date}
                                </span>
                            </div>

                            {store.detail.teacher_arr?.map(item => {
                                return (
                                    <div
                                        className={classNames(
                                            styles.plate_content_field,
                                            styles.plate_content_teacherWrap,
                                        )}
                                        key={item.teacher}
                                    >
                                        <label>{item.teacher}推荐</label>
                                        <div className={styles.plate_content_teacher}>
                                            <span>{item.sex_name}</span>
                                            <span>{item.region_name}</span>
                                        </div>
                                    </div>
                                )
                            })}
                        </div>
                    </div>

                    <div className={styles.plate}>
                        <div className={styles.plate_header}>派遣</div>
                        <div className={styles.plate_teacherContainerWrap}>
                            <TeacherCard
                                dispatch={store.detail.dispatch}
                                item={store.detail.teacher_dispatch?.[0]}
                                header={
                                    <>
                                        <div>组长</div>
                                        <span>培训师1</span>
                                    </>
                                }
                                onCancelDispatch={onCancelDispatch}
                                onDispatch={() => onDispatch(1)}
                            />

                            <TeacherCard
                                dispatch={store.detail.dispatch}
                                item={store.detail.teacher_dispatch?.[1]}
                                header={<div>培训师2</div>}
                                onCancelDispatch={onCancelDispatch}
                                onDispatch={() => onDispatch(2)}
                            />
                        </div>
                    </div>
                </div>
            </>
        )
    })
}

export default TeacherDispatch
